﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Zoomtel.Entity;
using Zoomtel.Entity.BIZ;
using Zoomtel.Persist.BIZ;
using Zoomtel.Persist.BIZ.Models;
using Zoomtel.Service.BIZ;
using Zoomtel.Web.Controllers;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
 
namespace Zoomtel.Web.Areas.Pub.Controllers
{
    [Description("产品接口")]
    public class ItemController :  PubModuleController
    {
        private readonly ItemService _service;
        private readonly ItemPromotionService _itemPromotionService;
        private Zoomtel.Cache.ICacheHandler _cache;
        private readonly ILoginInfo _loginInfo;//这里主要获取IP 和浏览器信息

        #region 公众号接口
        string APPID = "wxe58b825d6e17e63c";
        string APPSECRET = "c49bfda307d62df7e587bb901f6c655e";
        private string getGzhAccessToken()
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", APPID, APPSECRET);
            string access_token = _cache.Get<string>("wechat_gzh_access_token");
            if (access_token.IsNull())
            {
                string result = Zoomtel.Utils.Helpers.HttpHelper.HttpGet(url);
                var resultModel = JsonConvert.DeserializeObject<JObject>(result);
                access_token = resultModel["access_token"].ToString();
                _cache.Set<string>("wechat_gzh_access_token", access_token, 10);

            }
            return access_token;

        }
        #endregion

        #region 微信接口
        string wxappid = "wx7b43afd07dbc20ce";
        string wxappsecret = "71ba5b77685fbe754bf4081aeea3fec5";
        private string getAccessToken(string appid,string appsecret)
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, appsecret);
            string access_token = _cache.Get<string>("wechat_access_token");
            if (access_token.IsNull())
            {
                string result = Zoomtel.Utils.Helpers.HttpHelper.HttpGet(url);
                var resultModel = JsonConvert.DeserializeObject<JObject>(result);
                access_token = resultModel["access_token"].ToString();
                _cache.Set<string>("wechat_access_token", access_token, 10);

            }
            return access_token;

        }

        /// <summary>
        /// 获取小程序码
        /// </summary>
        /// <returns></returns>
        private string getUnlimited(string appid,string appsecret,string itemUrl,string itemid, string agentid)
        {
            //string appid = "";
            //string appsecret = "";
            string access_token = getAccessToken(appid,appsecret);
            string url =string.Format( "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}", access_token);
            string[] itemUrlList = itemUrl.Split('?');

            JObject obj = new JObject();
            //obj["page"] = itemUrlList[0];
            if (itemUrlList.Length >= 2)
            {
                obj["scene"] =  itemUrlList[1] + "&agentid=" + agentid+"&itemid="+itemid;

            }
            else
            {
                obj["scene"] = "agentid=" + agentid + "&itemid=" + itemid;
            }
            //obj["image_data"] = base64;
            string result = Zoomtel.Utils.Helpers.HttpHelper.HttpPostBase64(url, obj.ToString(), "application/json");

            return result;

        }

        #endregion

        #region 抖音接口
        string tikTokAppid = "tt972de1900816b937";
        string tikTokAppSecret = "1a80b64bbf4477a8b8f43b97f38225a0ecac7782";
        private string getTikTokAccessToken(string appid, string appsecret)
        {
            string url = string.Format("https://developer.toutiao.com/api/apps/token?grant_type=client_credential&appid={0}&secret={1}", tikTokAppid, tikTokAppSecret);
            string access_token = _cache.Get<string>("tiktok_access_token");
            //if (access_token.IsNull())
            //{
                string result = Zoomtel.Utils.Helpers.HttpHelper.HttpGet(url);
                var resultModel = JsonConvert.DeserializeObject<JObject>(result);
                access_token = resultModel["access_token"].ToString();
                _cache.Set<string>("tiktok_access_token", access_token, 10);

            //}
            return access_token;

        }


        private string getTikTokQrcode(string appid, string appsecret, string itemUrl,string itemid, string agentid)
        {
            string accessToken = getTikTokAccessToken(appid, appsecret);

            string url = "https://developer.toutiao.com/api/apps/qrcode";

            JObject obj = new JObject();
            obj["appname"] = "douyin";
            obj["access_token"] = accessToken;
            //obj["scene"] = "?userid=09862";
            obj["path"] = itemUrl+ "&agentid=" + agentid + "&itemid=" + itemid;
            //obj["image_data"] = base64;
            string result = Zoomtel.Utils.Helpers.HttpHelper.HttpPostBase64(url, obj.ToString(), "application/json");

            return result;

        }

        #endregion
        IHostingEnvironment _host;
        WechatLinkRepository _wechatLinkRepository;
        WechatImgCacheService _imgCacheService;
        public ItemController(ItemService service, ItemPromotionService itemPromotionService, WechatImgCacheService imgCacheService, IHostingEnvironment host, Zoomtel.Cache.ICacheHandler cache, WechatLinkRepository wechatLinkRepository ,ILoginInfo loginInfo)
        {
            _host = host;
            _wechatLinkRepository = wechatLinkRepository;
            _imgCacheService = imgCacheService;
            _itemPromotionService = itemPromotionService;
            _service = service;
            _cache = cache;
            _loginInfo=loginInfo;
        }



        [Description("幻灯片")]
        [HttpPost]
        [AllowAnonymous]
        public  Task<IResultModel> AdList()
        {

            return _service.Query(new ItemQueryModel() {
              
                IsTop=1,
                PageModel=new Persist.Query.QueryPagingModel()
                {

                    page=1,
                    rows=5
                }
            });
        }

        [Description("查询产品分类")]
        [HttpGet]
        [AllowAnonymous]
        public IResultModel QueryCat()
        {

            return _service.QueryCat();
        }
        [Description("查询产品")]
        [HttpPost]
        [AllowAnonymous]
        public Task< IResultModel> Query(ItemQueryModel model)
        {

            return  _service.Query(model);
        }
        [Description("获取评测详情")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<IResultModel> Get(string id)
        {

            var entity=await _service.Get(id);
            return ResultModel.Success(entity);
        }

        [Description("获取分销二维码")]
        [HttpGet]
        public async Task<IResultModel> MakeQrcode(string itemId,string type,string agentId)
        {
           var model=await _service.Get(itemId);

            string agentid = agentId;
            if(string.IsNullOrEmpty(agentId))
            {

                agentid = _loginInfo.Uid;
            }

            if (model == null)
            {
                return ResultModel.Failed("无产品信息");
            }

            if (type == "wechat")//生成小程序二维码
            {

             string qrcode=   getUnlimited(wxappid, wxappsecret,model.ItemUrl, itemId, agentid);
                return ResultModel.Success(qrcode);

            }else if (type == "tiktok")
            {
                string qrcode = getTikTokQrcode(tikTokAppid, tikTokAppSecret, model.ItemUrl, itemId, agentid);
                return ResultModel.Success(qrcode);

            }
            else
            {
                return ResultModel.Failed();

            }

        }

        [Description("产品点击")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<IResultModel> ItemClick(string itemId, string agentId)
        {
            if(string.IsNullOrEmpty(agentId))
            {
                return ResultModel.Failed("无分销商信息！");

            }
            var itemModel = await _service.Get(itemId);
            if (itemModel != null)
            {
                itemModel.ClickCount = itemModel.ClickCount + 1;
                _service.Update(itemModel);
                ItemPromotionEntity model = new ItemPromotionEntity();
                model.AgentId = agentId;
                model.ItemId = itemModel.ItemId.ToString();
                model.ClickTime = DateTime.Now;
                model.ClickType = "10";
                model.IPAddr = this.HttpContext.Connection.RemoteIpAddress.ToString();
                model.SettleFlag = "0";//未结算

                return await _itemPromotionService.Add(model);

            }
            else
            {
                return ResultModel.Failed("产品不存在！");
            }
        
      

        }

        [Description("产品广告播放")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<IResultModel> ItemAdPlay(string itemId, string agentId)
        {
            if (string.IsNullOrEmpty(agentId))
            {
                return ResultModel.Failed("无分销商信息！");

            }
            var itemModel =await _service.Get(itemId);
            if (itemModel != null)
            {
            
                ItemPromotionEntity model = new ItemPromotionEntity();
                model.AgentId = agentId;
                model.ItemId = itemModel.ItemId.ToString();
                model.ClickTime = DateTime.Now;
                model.ClickType = "20";
                model.IPAddr = this.HttpContext.Connection.RemoteIpAddress.ToString();
                model.SettleFlag = "0";//未结算

                return await _itemPromotionService.Add(model);

            }
            else
            {
                return ResultModel.Failed("产品不存在！");
            }
        }
        #region 微信转链相关方法

        /// <summary>
        /// 上传临时素材
        /// 返回media_id
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        private string UploadLinShiSuCai(string imgpath)
        {
            //string imgpath =_host.WebRootPath+$"/1.png";



            string access_token = getGzhAccessToken();
            string url2 = $"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type=image";

            //图片转为流
            Image img = new Bitmap(imgpath);
            MemoryStream stream = new MemoryStream();
            img.Save(stream, ImageFormat.Png);
            BinaryReader br = new BinaryReader(stream);
            byte[] data = stream.ToArray();
            stream.Close();



            var boundary = Guid.NewGuid().ToString("N");
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("User-Agent", "KnowledgeCenter");
            client.DefaultRequestHeaders.Remove("Expect");
            client.DefaultRequestHeaders.Remove("Connection");
            client.DefaultRequestHeaders.ExpectContinue = false;
            client.DefaultRequestHeaders.ConnectionClose = true;
            var content = new MultipartFormDataContent(boundary);
            content.Headers.Remove("Content-Type");
            content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
            var contentByte = new ByteArrayContent(data);
            content.Add(contentByte);
            contentByte.Headers.Remove("Content-Disposition");
            contentByte.Headers.TryAddWithoutValidation("Content-Disposition", $"form-data; name=\"media\";filename=\"1.png\"" + "");
            contentByte.Headers.Remove("Content-Type");
            contentByte.Headers.TryAddWithoutValidation("Content-Type", "image/png");
            try
            {
                var result2 = client.PostAsync(url2, content);
                if (result2.Result.StatusCode != HttpStatusCode.OK)
                    throw new Exception(result2.Result.Content.ReadAsStringAsync().Result);
                string jsonstr = result2.Result.Content.ReadAsStringAsync().Result;

                return jsonstr;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + ex.InnerException.Message);
            }

        }
        private string DownFile(string url)
        {
            //获取网站当前根目录
            string sWebRootFolder = _host.WebRootPath;
            //保存图片路径
            var savePath = "\\Upload\\download\\";
            //文件名
            string filename = System.IO.Path.GetFileName(url);
            //扩展名
            string extension = System.IO.Path.GetExtension(url);
            savePath = sWebRootFolder + savePath;
            //无夹创建
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            WebClient mywebclient = new WebClient();
            string allpath = savePath + filename;
            //下载文件
            mywebclient.DownloadFile(url, allpath);
            return allpath;
        }
        #endregion


        [AllowAnonymous]
        [HttpGet]
        [Description("获取微信小程序分享链接")]
        public async Task<IResultModel> getWecharMiniPrgShareUrl(string itemId,string agentID)
        {
            var model = _wechatLinkRepository.FindEntity(a => a.itemId == itemId && a.agentId == agentID);
            if (model != null)
            {
                return ResultModel.Success(model);
            }

            var itemModel = await _service.Get(itemId);
            var imgPath = DownFile(itemModel.PicUrl);

            string miniprogram_appid = "wx7b43afd07dbc20ce";//小程序APPID
            var imgCache = _imgCacheService.Get(itemId);
            if (imgCache == null)
            {

                string uploadResult = UploadLinShiSuCai(imgPath);
                JObject obj = JsonConvert.DeserializeObject<JObject>(uploadResult);
                imgCache = new Entity.BIZ.WechatImgCacheEntity();
                imgCache.mediaId = obj["media_id"].ToString();
                imgCache.url = obj["url"].ToString();
                imgCache.itemId = itemId;
                _imgCacheService.Add(imgCache);
            }




            string path = itemModel.ItemUrl + "&agentid=" + agentID+"&itemid="+itemId;
            //string imgPath = "https://mmbiz.qpic.cn/mmbiz_png/hEKM8cj9rNQI9luNic04fXLvgIVBAhosfm10xFTG3TfbeiafRsS9uMKQKeREtIRbxqzOb1AP6nGRHxf1fttF97Ng/640?wx_fmt=png&amp;wxfrom=200";


            string content = $"<p><a data-miniprogram-appid=\"{miniprogram_appid}\" data-miniprogram-path=\"{path}\" href=\"\"><img src=\"{imgCache.url}\" alt=\"{itemModel.ItemName}\" ></a></p> ";

            var artice = new JObject();
            artice["title"] = itemModel.ItemName;
            artice["thumb_media_id"] = imgCache.mediaId;
            artice["author"] = "心智";
            artice["show_cover_pic"] = 0;
            artice["content"] = content;
            artice["content_source_url"] = "";

            var arr = new JArray();
            arr.Add(artice);

            var PostObj = new JObject();

            PostObj["articles"] = arr;
            string access_token = getGzhAccessToken();

            string postUrl = $"https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={access_token}&type=image";

            string result = Zoomtel.Utils.Helpers.HttpHelper.HttpPost(postUrl, PostObj.ToString(), "application/json");

            var scMdid = JsonConvert.DeserializeObject<JObject>(result)["media_id"];

            //获取永久URL
            //string url3 = $"https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={access_token}";
            //var obj3 = new JObject();
            //obj3["media_id"] = scMdid;
            //result = Zoomtel.Utils.Helpers.HttpHelper.HttpPost(url3, obj3.ToString(), "application/json");

            string url3 = $"https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token={access_token}";
            //var obj3 = new JObject();
            //var obj3_1= new JObject();
            //obj3_1["media_id"] = scMdid;
            //obj3["msgtype"] = "mpnews";
            //obj3["msgtype"] = "mpnews";
            List<string> list = new List<string>();
            list.Add("o_RRd6Z1NT1DYVHVp-G_cl3OgVv8");
            list.Add("");
            //obj3["touser"] = list;

            var obj33 = new
            {
                mpnews = new
                {
                    media_id = scMdid
                },
                msgtype = "mpnews",
                touser = list
            };
            result = Zoomtel.Utils.Helpers.HttpHelper.HttpPost(url3, JsonConvert.SerializeObject(obj33), "application/json");

            var objSendModel = JsonConvert.DeserializeObject<JObject>(result);
            WechatLinkEntity link = new WechatLinkEntity();
            link.id = Guid.NewGuid().ToString("N");
            link.msgId = objSendModel["msg_id"].ToString();
            link.agentId = agentID;
            link.addtime = DateTime.Now;
            link.itemId = itemId;
            link.linkUrl = "";
            _wechatLinkRepository.Insert(link);

            return ResultModel.Success(link);
        }

        }
}
